#include"TcpServer.hpp"

//基于Tcpserver 实现一个echoserver,本质上就是控制OnMessage 函数

// void OnMessage(const PtrConnection& conn , Buffer* buf)
// {
//     //读取接受缓冲区中的数据进行处理

// }

// int main()
// {
//     TcpServer server(8888);
//     server.SetThreadCount(3);
//     server.EnableInactiveRelease(4);
//     server.SetMessageCallback();
//     server.SetAnyEventCallback();
//     server.SetConnectedCallback();
//     server.Start();
//     return 0;
// }

class EchoServer
{
private:
    TcpServer _server;
private:
    void OnMessage(const PtrConnection& conn , Buffer* buf)
    {
        //读取接受缓冲区中的数据进行处理
        conn->Send(buf->ReadPostion() ,buf->ReadAbleSize());
        buf->MoveReadOffset(buf->ReadAbleSize());
        //短连接
        conn->Shutdown();
    }
    void OnConnected(const PtrConnection& conn)
    {
        DBG_LOG("new connection: %p" , conn.get());
    }
    void OnClosed(const PtrConnection& conn)
    {
        DBG_LOG("remove connection: %p" , conn.get());
    }
    
public:
    //设置回调
    EchoServer(int port):_server(port)
    {
        _server.SetThreadCount(3);
        _server.EnableInactiveRelease(4);
        _server.SetMessageCallback(std::bind(&EchoServer::OnMessage , this , std::placeholders::_1 , std::placeholders::_2));
        _server.SetCloseCallback(std::bind(&EchoServer::OnClosed , this , std::placeholders::_1));
        _server.SetConnectedCallback(std::bind(&EchoServer::OnConnected,this , std::placeholders::_1));
    }
    void Start()
    {
        _server.Start();
    }
};